<?php

class Application_Model_Img
{
    public static function getImage($filename, $type, $hight)
    {
        $dirCache = './thumbs/' . $type . '/' . $hight . '/';
        
        if(!is_dir($dirCache)) {
            mkdir($dirCache);
        }
        
        $fileCache = $dirCache . $filename;
        
        $imgCache = imagecreatefromjpeg($fileCache);
        
        if ($imgCache) {
            $thumb = $imgCache;
        } else {
            $dir = './images/' . $type . '/' . $filename;
        
            $img = imagecreatefromjpeg($dir);
        
            $imgX = imagesx($img);
            $imgY = imagesy($img);
        
            $width = ($imgX*$hight)/$imgY;
            $width = (int) $width;

            $thumb = imagecreatetruecolor($width, $hight);
        
            imagecopyresized($thumb, $img, 0, 0, 0, 0, $width, $hight, $imgX, $imgY);
            
            imagejpeg($thumb, $fileCache);
        }
        
        return $thumb;
    }
    
    public static function saveImage($form)
    {
        $tmpDir = realpath(dirname('.')) . '/images/tmp/';
        $dir = realpath(dirname('.')) . '/images/' . $form->type_picture->getValue() . '/';
        
        $result = FALSE;
        
        if($form->file_picture->isUploaded() && $form->file_picture->getValue()) {
            $file = $form->file_picture->getValue();
            $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
            $newName = substr(md5(time()), 0, 8) . '.' . $ext;

            copy($tmpDir.$file, $dir.$newName);
            unlink($tmpDir.$file);
            
            $result = $newName;
        }
        
        return $result;
    }
}
